<template>
  <div
    :class="{
      'field-upload': true,
      lapse: (tableStatus && (tableStatus.isLapse === '2'||tableStatus.isLapse === '3')) || readOnly,
      disabled: disabled || readOnly
    }"
  >
    <el-upload
      action="#"
      :data="{}"
      :auto-upload="true"
      :file-list="localValue"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :limit="limit"
      :headers="{ Authorization: findToken(), Token: findToken() }"
      :on-success="handleSuccess"
      :disabled="disabled && findDisabled()"
      :before-upload="beforeUpload"
      multiple
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <div
      ref="bigImage"
      class="draggableIMg"
      id="imgShow"
      @mousewheel="rollImg(this)"
      v-drag
      draggable="false"
      v-if="dialogVisible"
    >
      <img
        :src="dialogImageUrl"
        :style="{ transform: 'rotateZ(' + deg + 'deg)' }"
        class="image-show"
      />
      <div class="operation-icon">
        <i
          v-if="dialogImageUrl && openOcr && findDisabled()"
          class="el-icon-full-screen"
          title="转文字"
          @click="doOcr(dialogImageUrl)"
        ></i>
        <i
          v-if="dialogImageUrl"
          class="el-icon-refresh"
          title="旋转"
          @click="rotate"
        ></i>
        <i
          v-if="dialogImageUrl"
          class="el-icon-error"
          title="关闭"
          @click="closeImage"
        ></i>
      </div>
    </div>
  </div>
</template>

<script>
// import Cookies from "js-cookie";
import { mapGetters, mapState } from "vuex";

export default {
  data() {
    return {
      urlbase: `?x-image-process=image/resize,m_lfit,h_100,w_100`,
      baseUrl: '',
      localValue: [],
      dialogImageUrl: "",
      dialogVisible: false,
      deg: 0,
      zoom: 1,
      disabled: false,
      coreList: [],
      coreIds: [],
      selectEdcTopicId: null,
      subjectId: null,
      subjectCode: null
    };
  },
  props: {
    value: {
      type: String
    },
    tableField: {
      type: Object
    },
    tableStatus: {
      type: Object
    }
  },
  computed: {
    ...mapState({
      subjectInfo: state => state.treatment.subjectInfo
    }),
    limit: function() {
      let quantity = this.tableField.fieldVariableValue.quantity;
      if (typeof quantity === "string") {
        return parseInt(quantity);
      } else if (typeof quantity === "number") {
        return quantity;
      } else {
        return 1;
      }
    },
    openOcr: function() {
      return this.tableField.fieldVariableValue.doOcr == 0; //0开启 1关闭
    },
    readOnly: function() {
      return (
        this.tableField.readOnly === 0 ||
        (this.tableStatus &&
          (this.tableStatus.isLapse === '2' ||
          this.tableStatus.isLapse === '3' ||
            this.tableStatus.frozen === '2'))
      );
    }
  },
  watch: {
    value: {
      handler: function(val) {
        if (val) {
          if (val.indexOf(",") >= 0) {
            this.localValue = val.split(",").map(item => {
              return { url: item + this.urlbase };
            });
          } else {
            this.localValue = [{ url: val + this.urlbase }];
          }
        } else {
          this.localValue = [];
        }
      },
      immediate: true,
      deep: true
    },
    "tableField.controlled": {
      handler: function(val) {
        this.disabled = val;
        val && this.$emit("input", "");
      },
      deep: true,
      immediate: true
    }
  },
  created() {

  },
  methods: {
    findDisabled: function() {
      return false;
    },
    handleSuccess: function(response, file) {
      const {
        name,
        status,
        response: { code, data: url, message }
      } = file;
      if (status == "success") {
        if (code == 200) {
          this.localValue.push({
            name,
            url: url + this.urlbase
          });
          let newUrls = [];
          this.localValue.forEach(element => {
            newUrls.push({
              name: element.name,
              url: element.url.split("?")[0]
            });
          });
          console.log("this.localValue", this.localValue);
          if (newUrls.length == 1) {
            this.$emit("input", newUrls[0].url);
          } else {
            this.$emit("input", newUrls.map(item => item.url).join(","));
          }
        } else {
          this.$message.error(message);
        }
      }
    },
    findToken: function() {
      // return Cookies.get("zvfptoken");
    },
    handleRemove(file) {
      const { status, url } = file;
      if (status == "success") {
        let index = this.localValue.findIndex(item => item.url == url);
        if (index > -1) {
          this.localValue.splice(index, 1);
        }
      }
      let newUrls = [];
      this.localValue.forEach(element => {
        newUrls.push({
          name: element.name,
          url: element.url.split("?")[0]
        });
      });
      if (newUrls.length == 0) {
        this.$emit("input", "");
      } else if (newUrls.length == 1) {
        this.$emit("input", newUrls[0].url);
      } else {
        this.$emit("input", newUrls.map(item => item.url).join(","));
      }
    },
    //打开预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url.split("?")[0];
      this.dialogVisible = true;
      console.log("handlePictureCardPreview=", file.url, this.localValue);
    },
    //关闭
    closeImage() {
      this.dialogVisible = false;
    },
    // 旋转
    rotate() {
      this.deg += 90;
      if (this.deg >= 360) {
        this.deg = 0;
      }
    },
    rollImg() {
      //获取当前页面的缩放比,若未设置zoom缩放比，则为默认100%，即1，原图大小
      var zoom = parseInt(this.$refs.bigImage.style.zoom) || 100;
      //event.wheelDelta 获取滚轮滚动值并将滚动值叠加给缩放比zoom,wheelDelta统一为±120，其中正数表示为向上滚动，负数表示向下滚动
      zoom += event.wheelDelta / 50;
      /* 最小范围 和 最大范围 的图片缩放尺度 */
      if (zoom >= 30 && zoom < 250) {
        this.$refs.bigImage.style.zoom = zoom + "%";
      }
      this.zoom = zoom / 100;
      return false;
    },
    beforeUpload (file) {
      this.$message.error("功能正在开发中！");
      // const isJPG =
      //   file.type == "image/jpg" ||
      //   file.type == "image/jpeg" ||
      //   file.type == "image/png" ||
      //   file.type == "image/webp";
      // const isLt2M = file.size / 1024 / 1024 < 50;
      // if (!isJPG) {
      //   this.$message.error("请上传JPG,PNG,JPEG,WEBP格式图片!");
      // }
      // if (!isLt2M) {
      //   this.$message.error("上传大小不能超过 50MB!");
      // }
      // return isJPG && isLt2M;
    }
  },
  directives: {
    drag(el) {
      let oDiv = el; // 当前元素
      // 禁止选择网页上的文字
      document.onselectstart = function() {
        return false;
      };
      oDiv.onmousedown = function(e) {
        // 鼠标按下，计算当前元素距离可视区的距离
        let disX = e.clientX - oDiv.offsetLeft;
        let disY = e.clientY - oDiv.offsetTop;
        document.onmousemove = function(e) {
          // 通过事件委托，计算移动的距离
          let l = e.clientX - disX;
          let t = e.clientY - disY;
          // 移动当前元素
          oDiv.style.left = l + "px";
          oDiv.style.top = t + "px";
        };
        document.onmouseup = function(e) {
          document.onmousemove = null;
          document.onmouseup = null;
        };
        // return false不加的话可能导致黏连，相当于onmouseup失效
        return false;
      };
    }
  }
};
</script>

<style>
.draggableIMg {
  position: fixed;
  top: 100px;
  right: 100px;
  cursor: pointer;
  z-index: 999;
}

.operation-icon {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 30px;
  background-color: rgba(190, 223, 255, 0.6);
  padding: 10px;
  border-radius: 20px;
  cursor: pointer;
}

.image-show {
  width: auto;
  height: 60vh;
  object-fit: contain;
}
</style>

<style lang="scss" scoped>
.lapse >>> .el-icon-plus,
.disabled >>> .el-icon-plus {
  display: none;
}
</style>